var prefix = "/sysContract";

var myPdf = [],myPdfYi = [], myPdfItem = {name: '', url: '', id: '',contractType:1,orderId:0}
let EditVerify = []//审核时候的错误
var remove = (id,number) => {
    if(number==0){
        if (myPdf.find(item => item.id == id + '-0')) {
            //删除这条
            myPdf = myPdf.filter((item) => {
                return !(id + '-0').includes(item.id)
            });
            $('#myUpdataDiv').find('div[myid=' + id + '-0]').remove();
        }
    }else{

        if (myPdfYi.find(item => item.id == id + '-0')) {
            //删除这条
            myPdfYi = myPdfYi.filter((item) => {
                return !(id + '-0').includes(item.id)
            });
            $('#myUpdataDivYi').find('div[myid=' + id + '-0]').remove();
        }
    }

}
var openPdf = (id) => {
    let myItem = myPdf.find(item => item.id == id + '-0')
    if (myItem) {
        if(myItem.contractType==0){
            let a= document.createElement("a");
            a.href=`/jzApi/jazUserAunt/userOrderExport?orderId=${myItem?.orderId}`
            a.download="合同.docx"
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            return false;
        }
        let toIndex = layer.open({
            type: 2,
            area: ['80%', '80%'],
            fixed: false, //不固定
            maxmin: true,
            content: myItem.url
        });
        layui.full(toIndex)
    }
}

layui.use(['form', 'xmSelect', 'upload', 'laydate'], function () {
    var form = layui.form;
    var layer = layui.layer;
    var upload = layui.upload;
    var xmSelect = layui.xmSelect;
    var laydate = layui.laydate;
    var loading,myDataList1=[],myDataList2=[];
    if($('#type').val()=='add') {
        $('#mySelect1').attr("disabled", true);
        AjaxGet('/sysContract/initiator').then(function (response) {
            if (response.code == '0') {
                myDataList1 = response.data
                //设置select
                $('#mySelect1').empty();
                $('#mySelect1').append($('<option>', {
                    value: '',
                    text: '请选择姓名'
                }))
                response.data.forEach(item => {
                    $('#mySelect1').append($('<option>', {
                        value: item.initiateId,
                        text: item.nameJia+'-'+item.phoneJia
                    }))
                })
                $('#mySelect1').attr("disabled", false);
                form.render('select');
                selectInput($('#mySelect1'), 10)
            }
        }).catch(error => {
            layer.msg(error.msg)
        })
    }
	/**
	 * 类型选择器多选
	 */
	var ctState = xmSelect.render({
		el: '#contractState',
		name: 'projectId',
        max:1,
		data: [],
        maxMethod(seles, item) {
            layer.msg('最大只能选择1个')
        },
	})
	/**
	 * 选择器参数请求
	 */
	const setXmSelect=(myValues)=>{
		AjaxGet('/userAunt/seleProject').then(function (response) {
			let str = [];
			response.data.map(function (v) {
				str.push({
					name: v.name,
					value: v.id,
					disabled: $('#type').val()!='add',
                    selected: myValues.includes(v.id),
				})
			});
			ctState.update({
				data: str,
				autoRow: true,
			})
		}).catch(function (error) {
			layer.msg(error.msg)
		})
	}

    const setList2 = (myList=[]) => {
        if(myList.length>0){
            $("#mySelect2").empty();
            $('#mySelect2').append($('<option>', myList[0]))
            form.render('select');
        }else{
            $('#mySelect2').attr("disabled", true);
            AjaxGet('/sysContract/signed').then(function (response) {
                if (response.code == '0') {
                    myDataList2 = response.data
                    //设置select
                    $('#mySelect2').empty();
                    $('#mySelect2').append($('<option>', {
                        value: '',
                        text: '请选择姓名',
                    }))
                    response.data.forEach(item => {
                        $('#mySelect2').append($('<option>', {
                            value: item.signingId,
                            text: item.nameYi+'-'+item.phoneYi,
                        }))
                    })
                    $('#mySelect2').attr("disabled", false);
                    form.render('select');
                    selectInput($('#mySelect2'), 10)
                }
            }).catch(error => {
                layer.msg(error.msg)
            })
        }
    }

	form.on('select(mySelect1-filter)', function(data){
		var value = data.value; // 获得被选中的值
		if(value!=""){
			let item=myDataList1.find((itemdata)=> itemdata.initiateId==value)
			$('#phoneJia').val(item.phoneJia)
			$('#homeAddressJia').val(item.homeAddressJia)
			$('#nameJia').val(item.nameJia)
            setXmSelect(item.projectId ? item.projectId.split(',') : [])

            // if(item.interviewFormat=='0'){
                //下
                $('#phoneYi').val('')
                $('#homeAddressYi').val('')
                setList2()
            // }else{
            //     //上导入
            //     $('#phoneYi').val(item.phoneYi)
            //     $('#homeAddressYi').val(item.homeAddressYi)
            //     setList2([{
            //         value: item.signingId,
            //         text: item.nameYi,
            //         selected:true,
            //         disabled:true
            //     }])
            // }
		}else {
            $('#phoneJia').val('')
            $('#homeAddressJia').val('')
            $('#phoneYi').val('')
            $('#homeAddressYi').val('')
            setList2([{
                value: '',
                text: '请先选择发起方',
                selected:true,
                disabled:true
            }])
            setXmSelect([])
		}
	});
    form.on('select(mySelect2-filter)',function(data){
        var value = data.value; // 获得被选中的值
        if(value!=""){
            let item=myDataList2.find((itemdata)=> itemdata.signingId==value)
            $('#phoneYi').val(item.phoneYi)
            $('#homeAddressYi').val(item.homeAddressYi)
            $('#nameYi').val(item.nameYi)
            $('#identityCardYi').val(item.identityCardYi)
        }else {
            $('#phoneYi').val('')
            $('#homeAddressYi').val('')
            $('#identityCardYi').val('')
        }
    });


    let myStartDate,myEndDate;
    myStartDate=laydate.render({
        elem: "#startTime",
        trigger: 'click',
        max:"9999-12-31",
        done: function (value, dates) {
            myEndDate.config.min ={
                year:dates.year,
                month:dates.month-1, //关键
                date: dates.date,
                hours: dates.hours,
                minutes: dates.minutes,
                seconds : dates.seconds
            };
        }
    });
    myEndDate=laydate.render({
        elem: "#endTime",
        trigger: 'click',
        min:"1888-01-01",
        done: function (value, dates) {
            myStartDate.config.max={
                year:dates.year,
                month:dates.month-1,//关键
                date: dates.date,
                hours: dates.hours,
                minutes: dates.minutes,
                seconds : dates.seconds
            }
        }
    });




    upload.render({
        elem: '#contract'
        , url: '/common/sysFile/upload'
        , accept: 'file'
        , exts: 'pdf'
        , acceptMime: 'application/pdf'
        , before: function (obj) {
            if(myPdf.length==1){
                layer.msg('上传已达上限，请删除在传')
                return false
            }
            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
            for (var key in files) {
                if (!myPdf.find(item => item.id == key)) {
                    myPdfItem = {name: '', url: '', id: '',contractType:1,orderId:0}
                    myPdfItem.name = files[key].name
                    myPdfItem.id = key
                }
            }
            //读取本地文件
            obj.preview(function (index, file, result) {
                console.log(file.Name);
            });
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res, index) {
            layer.close(loading);
            if (res.code == 0) {
                if(myPdf.length<1){
                layer.msg('上传成功');
                myPdfItem.url = res.data
                myPdf.push(myPdfItem)
                delete this.files[index]
                $('#myUpdataDiv').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="../../../img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						<a href="#" onclick="remove(${myPdfItem.id},0);"> 
						<img  class="closeUpload" src="../../img/close.png" >	
						</a>
				</div>
				`)
            }else {
                layer.msg('上传已达上限，请删除在传')
            }


            } else {
                layer.msg('上传失败,请检查');
            }

        }
    })
    upload.render({
        elem: '#contractYi'
        , url: '/common/sysFile/upload'
        , accept: 'file'
        , exts: 'pdf'
        , acceptMime: 'application/pdf'
        , before: function (obj) {
            if(myPdfYi.length==1) {
                layer.msg('上传已达上限，请删除在传')
                return false
            }
            var files = this.files = obj.pushFile();  //将每次选择的文件追加到文件队列
            for (var key in files) {
                if (!myPdfYi.find(item => item.id == key)) {
                    myPdfItem = {name: '', url: '', id: '',contractType:1,orderId:0}
                    myPdfItem.name = files[key].name
                    myPdfItem.id = key
                }
            }
            //读取本地文件
            obj.preview(function (index, file, result) {
                console.log(file.Name);
            });
            loading = layer.load({
                type: 3,
                content: '加载中...',
            });//在post之前定义loading
        }
        , done: function (res, index) {
            layer.close(loading);
            if (res.code == 0) {
                if(myPdfYi.length<1){
                layer.msg('上传成功');
                myPdfItem.url = res.data
                myPdfYi.push(myPdfItem)
                delete this.files[index]
                $('#myUpdataDivYi').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="../../../img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						<a href="#" onclick="remove(${myPdfItem.id},1);"> 
						<img  class="closeUpload" src="../../img/close.png" >	
						</a>
				</div>
				`)
            }else {
                layer.msg('上传已达上限，请删除在传')
            }


            } else {
                layer.msg('上传失败,请检查');
            }

        }
    })
    if($('#type').val()=='info'){
        let list=$('#pdfList').val()
        let listYi=$('#pdfListYi').val()
        list=list?list.split(','):[]
        listYi=listYi?listYi.split(','):[]

        let projectId=$('#projectId').val()
        setXmSelect(projectId ? projectId.split(',') : [])

        //回显
        for (let i = 0; i <list.length ; i++) {
            myPdfItem= {name: '文件'+(i+1), url: '', id: '',contractType:$('#contractType').val(),orderId:$('#orderId').val()}
            myPdfItem.url = list[i]
            myPdfItem.id = i
            $('#myUpdataDiv').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="../../../img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						 
				</div>
				`)
            myPdfItem.id = i+'-0'
            myPdf.push(myPdfItem)
        }
        for (let i = 0; i <listYi.length ; i++) {
            myPdfItem= {name: '文件'+(i+1), url: '', id: '',contractType:$('#contractType').val(),orderId:$('#orderId').val()}
            myPdfItem.url = list[i]
            myPdfItem.id = i
            $('#myUpdataDivYi').prepend(`
				<div href="#" class="mybutton upload " myid="${myPdfItem.id}" onclick="openPdf(${myPdfItem.id});" > 
					    <img class="upImg" src="../../../img/pdf.png">
						<span style=" color: #000;   text-align: center; ">
							${myPdfItem.name}</span>
						<input value="${myPdfItem.id}" class="layui-hide">
						 
				</div>
				`)
            myPdfItem.id = i+'-0'
            myPdfYi.push(myPdfItem)
        }
    }
    //提交事件
    form.on('submit(submit)', function (data) {
        console.log('data', data.field)
        if($('#type').val()=='info'){
            parent.load();
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
            return  false
        }
        //身份证
        if(!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(data.field.identityCardJia)){
            layer.msg('身份证号不合法')
            return false
        }
        if( ''==data.field.address){
            layer.msg('请输入服务地址')
            return false
        }
        if (myPdf.length == 0) {
            layer.msg('请上传用户合同pdf')
            return false
        }
        if (myPdfYi.length == 0) {
            layer.msg('请上传阿姨合同pdf')
            return false
        }

        let mydata = data.field
        mydata.identityCardYi=$('#identityCardYi').val()
        if (mydata.signingId == '') {
            layer.msg('请选择签约方')
            return false
        }
        mydata.contractNamePath = ''
        myPdf.forEach(item => {
            mydata.contractNamePath += item.url + ','
        })
        mydata.contractNameYiPath = ''
        myPdfYi.forEach(item => {
            mydata.contractNameYiPath += item.url + ','
        })
        delete mydata.file
        mydata.contractNamePath = mydata.contractNamePath.substring(0, mydata.contractNamePath.length - 1)
        mydata.contractNameYiPath = mydata.contractNameYiPath.substring(0, mydata.contractNameYiPath.length - 1)

        //
        mydata.startTime=mydata.startTime+' 00:00:00'
        mydata.endTime=mydata.endTime+' 00:00:00'

        //
        mydata.nameJia=$('#nameJia').val()
        mydata.nameYi=$('#nameYi').val()


        AjaxPost(prefix + "/insertSysContract", mydata).then(res => {
            parent.layer.msg("操作成功");
            parent.load();
            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
            parent.layer.close(index);
        }).catch(e => {
            layer.msg(e.msg);
        })

        return false;
    });


});